package com.htdz.controller;

import com.htdz.entity.Users;
import com.htdz.entity.UsersInfo;
import com.htdz.entity.UsersRole;
import com.htdz.service.ResourceService;
import com.htdz.service.UsersService;
import com.htdz.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public UsersService usersService;
    @Autowired
    public RedisUtil redisUtil;
    @Autowired
    public ResourceService resourceService;

    /**
     * 登录验证
     * @param usersName
     * @param inputPassword
     * @return
     */
    @RequestMapping("/checkIn")
    public String login(HttpServletRequest request,Model model, String usersName, String inputPassword){
        Users users = usersService.login(usersName,inputPassword);
        if(users == null){
            model.addAttribute("message","用户名或密码错误");
            return "login";
        }

        UsersInfo usersInfo = new UsersInfo();
        usersInfo.setUsersId(users.getUsersId());
        usersInfo.setUsersName(users.getUsersName());
        model.addAttribute("usersInfo",usersInfo);
        /*//保存登录信息至redis
        redisUtil.saveUserInfo2Redis(usersInfo);*/

        HttpSession session = request.getSession();
        session.setAttribute("usersInfo",usersInfo);

        Map map = new HashMap<>();
        map.put("usersId",usersInfo.getUsersId());
        List<UsersRole> usersRoleList = usersService.listUsersRole(map);
        //一个用户如有多个角色，取资源的全集
        Map menuMap = resourceService.listMenuResource(usersRoleList);
        session.setAttribute("menuMap",menuMap);

        return "home";
    }

    /**
     * 退出登录
     * @param model
     * @param usersName
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,Model model, String usersName){
        Map map = new HashMap();
        map.put("usersName",usersName);
        Users users = usersService.getUsers(map);
        UsersInfo usersInfo = new UsersInfo();
        usersInfo.setUsersId(users.getUsersId());
        usersInfo.setUsersName(users.getUsersName());
        /*redisUtil.deleteUserInfo2Redis(usersInfo);*/
        request.getSession().removeAttribute("usersInfo");
        return "login";
    }
}
